import { Request, Response } from "express";
import { AppDataSource } from "../config/db";
import { UserModel } from "../models/User.model";
import { success, fail } from "../utils/response";
import { JwtUtils } from "../utils/jwt.utils";
import { Role, JwtPayload } from "../types";
import { BcryptUtil, decryptAESDefault } from "../utils/bcrypt.utils";

const userRepo = AppDataSource.getRepository(UserModel);

export const login = async (req: Request, res: Response) => {
  let { username, password } = req.body;
  username = decryptAESDefault(username);
  password = decryptAESDefault(password);
  const user: UserModel | null = await userRepo.findOne({
    where: { username },
  });
  if (!user || !(await BcryptUtil.verifyPassword(password, user.password))) {
    return fail(res, 401, "用户名或密码错误");
  }

  const tokenOrigin = {
    userId: user.id,
    username: user.username,
    role: user.role as Role,
  } as JwtPayload;
  // 根据 字符串字面量类型 定义 role 类型
  const token = JwtUtils.generateToken(tokenOrigin);
  console.log("Set session user:", tokenOrigin);
  console.log("Session ID:", req.sessionID);
  req.session.user = tokenOrigin;
  success(res, {
    token,
    data: { userId: user.id, username: user.username, role: user.role },
  });
};

export const register = async (req: Request, res: Response) => {
  const { username, password } = req.body;
  const user = await userRepo.findOne({ where: { username } });
  if (user) {
    return fail(res, 400, "用户名已存在");
  }

  const hashPassword = await BcryptUtil.encodePassword(password);
  const newUser = userRepo.create({
    username,
    password: hashPassword,
    role: "user",
  });
  await userRepo.save(newUser);
  success(res, {
    id: newUser.id,
    username: newUser.username,
    role: newUser.role,
  });
};

export const logout = async (req: Request, res: Response) => {
  req.session.user = undefined;
  req.session.destroy((err) => {
    if (err) {
      console.error(err);
      return fail(res, 500, "服务器内部错误");
    }
    success(res, "登出成功");
  });
};
